<?php

namespace app\admin\controller;

use app\admin\model\TeacherArea;
use app\admin\model\TeacherSubscribe;
use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 教师身份信息管理
 *
 * @icon fa fa-circle-o
 */
class IdentityInfo extends Backend
{

    protected $searchFields = 'id,user_id,name,phone';
    protected $selectpageFields = 'id,user_id,name,phone';
    /**
     * IdentityInfo模型对象
     * @var \app\admin\model\IdentityInfo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\IdentityInfo;
//        $param = $this->request->param();
//        $week_name = [];
//        if(isset($param['ids'])&&$param['ids']){
//            $this->model = new \app\admin\model\IdentityInfo;
//            $info = $this->model->find($param['ids']);
//            $week = [1,2,3,4,5,6,7];
//            $subscribe = TeacherSubscribe::where(['teacher_id'=>$info['user_id']])->where('class_id >0')->column('week');
//            $week_arr = array_diff($week,$subscribe);
//            $week_arr = array_values($week_arr);
//            sort($week_arr);
//            $data['week'] = $week_arr;
//            $identity_info_model = new \app\admin\model\IdentityInfo();
//            $getWeekList = $identity_info_model->getWeekList();
//            foreach ($week_arr as $k=>$v){
//                $week_name[$v] = isset($getWeekList[$v]) ? $getWeekList[$v] : '';
//            }
//        }else{
//            if(isset($param['keyValue'])&&$param['keyValue']){
//                $keyValue = explode(',',$param['keyValue']);
//                foreach ($keyValue as $k=>$v){
//                    $week_name[$k]['id'] = $v;
//                    $week_name[$k]['name'] = $v;
//                }
//            }else{
//                $identity_info_model = new \app\admin\model\IdentityInfo();
//                $getWeekList = $identity_info_model->getWeekList();
//                $week_name = $getWeekList;
//            }
//        }
//        $week_name = (object)$week_name;
//        $this->assign('getWeekName', $week_name);
//        $this->assignconfig("getWeekName", $week_name);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            // 获取区域列表数据，传递给视图
            $area_arr = TeacherArea::get_arr();
            $this->view->assign('areaList', $area_arr);
            $this->assignconfig('areaList', $area_arr);
            
            // 获取学历列表数据，传递给视图
            $educationList = \app\admin\model\IdentityInfo::xl();
            $educationSearchList = [];
            foreach ($educationList as $education) {
                $educationSearchList[$education] = $education;
            }
            $this->view->assign('educationList', $educationList);
            $this->assignconfig('educationList', $educationSearchList);
            
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        // 获取筛选参数，处理区域筛选
        $filter = json_decode($this->request->get("filter", ''), true);
        $op = json_decode($this->request->get("op", '', 'trim'), true);
        
        // 处理区域筛选：如果筛选area字段，且传入的是区域名称（中文），需要转换为区域ID
        if (isset($filter['area']) && !empty($filter['area'])) {
            $filter_value = $filter['area'];
            // 如果不是数字（可能是区域名称），需要转换为区域ID
            if (!is_numeric($filter_value)) {
                $area_arr = TeacherArea::get_arr();
                $area_name_arr = array_flip($area_arr); // 反转数组，变成 名称=>ID 的映射
                
                if (isset($area_name_arr[$filter_value])) {
                    // 精确匹配区域名称
                    $filter['area'] = $area_name_arr[$filter_value];
                } else {
                    // 模糊匹配区域名称，找到所有匹配的ID
                    $matched_ids = [];
                    foreach ($area_arr as $id => $name) {
                        if (mb_strpos($name, $filter_value) !== false) {
                            $matched_ids[] = $id;
                        }
                    }
                    if (!empty($matched_ids)) {
                        // 如果有多个匹配，需要特殊处理：使用 OR 条件或取第一个
                        // 这里使用第一个匹配的ID，如果需要多个匹配可以使用逗号分隔
                        $filter['area'] = implode(',', $matched_ids);
                    } else {
                        // 没有匹配的区域，设置为不存在的ID，使查询返回空结果
                        $filter['area'] = '0';
                    }
                }
            }
            
            // 确保area字段使用FIND_IN_SET操作符
            if (!isset($op['area']) || empty($op['area'])) {
                $op['area'] = 'FIND_IN_SET';
            }
            
            // 重新设置请求参数
            $this->request->get(['filter' => json_encode($filter)]);
            $this->request->get(['op' => json_encode($op)]);
        }
        
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model->with([
            'user' => function ($query) {
                $query->withField('nickname');
            },'club' => function ($query) {
                $query->withField('name');
            },'clubDtl' => function ($query) {
                $query->withField('name');
            }]);
        $area_arr = TeacherArea::get_arr();

        $list = $list->where($where)->where(['identity_type'=>'教师'])
            ->order($sort, $order)
            ->paginate($limit)->each(function ($row) use($area_arr) {
                $area = explode(',',$row['area']);
                $area_name = '';
                foreach ($area as $k=>$v){
                    $area_name .= isset($area_arr[$v]) ? $area_arr[$v].',' : '';
                }
                $row['area_name'] = trim($area_name,',');
            });

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            // 获取学历选项数据
            $educationList = \app\admin\model\IdentityInfo::xl();
            $this->view->assign('educationList', $educationList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $info = \app\admin\model\IdentityInfo::where(['user_id'=>$params['user_id']])->find();
        if($info){
            $this->error('已有'.$info['identity_type'].'身份,无法添加');
        }
        if($params['start_time']&&$params['end_time']){
            $params['appointment_time'] = $params['start_time'].' - '.$params['end_time'];
        }
        unset($params['start_time'],$params['end_time']);
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['identity_type'] = '教师';
            $user = User::where(['id'=>$params['user_id']])->find();
            $params['name'] = $user['nickname'];

            // 如果有生日，根据生日计算年龄
            if (!empty($params['birthday'])) {
                $params['age'] = $this->calculateAge($params['birthday']);
            }

            User::where(['id'=>$params['user_id']])->update(['identity_type'=>'教师']);

            $week = explode(',',$params['appointment_time_week']);
            $sub = TeacherSubscribe::up_subscribe($week,$params['user_id']);
            if($sub['code'] == 0){
                $this->error($sub['msg']);
            }
            if($params['name']&&$params['phone']&& $params['health_certificate']&&$params['identity_card_img']&&$params['no_crime']){
                $params['is_all'] = '是';
            }else{
                $params['is_all'] = '否';
            }
            // 设置默认显示状态
            if (!isset($params['main_status']) || empty($params['main_status'])) {
                $params['main_status'] = 1;
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function pull(){
        $param = $this->request->param();
        $week_name = [];
        if(isset($param['user_id'])&&$param['user_id']){
            if(isset($param['keyValue'])&&$param['keyValue']){
                $keyValue = explode(',',$param['keyValue']);
                foreach ($keyValue as $k=>$v){
                    $week_name[$k]['id'] = $v;
                    $week_name[$k]['name'] = $v;
                }
//                $week = [1,2,3,4,5,6,7];
//                $subscribe = TeacherSubscribe::where(['teacher_id'=>$param['user_id']])->where('class_id >0')->column('week');
//                $week_arr = array_diff($week,$subscribe);
//                $week_arr = array_values($week_arr);
//                sort($week_arr);
//                $data['week'] = $week_arr;
//                $identity_info_model = new \app\admin\model\IdentityInfo();
//                $getWeekList = $identity_info_model->getWeekList();
//
//                $keyValue = explode(',',$param['keyValue']);
//
//                foreach ($week_arr as $k=>$v){
//                    $name = isset($getWeekList[$v]) ? $getWeekList[$v] : '';
//                    if(in_array($name,$keyValue)){
//                        $week_name[$k]['id'] = $name;
//                        $week_name[$k]['name'] = $name;
//                    }
//                }
            }else{
                $week = [1,2,3,4,5,6,7];
                $subscribe = TeacherSubscribe::where(['teacher_id'=>$param['user_id']])->where('class_id >0')->column('week');
                $week_arr = array_diff($week,$subscribe);
                $week_arr = array_values($week_arr);
                sort($week_arr);
                $data['week'] = $week_arr;
                $identity_info_model = new \app\admin\model\IdentityInfo();
                $getWeekList = $identity_info_model->getWeekList();
                foreach ($week_arr as $k=>$v){
                    $week_name[$k]['id'] = isset($getWeekList[$v]) ? $getWeekList[$v] : '';
                    $week_name[$k]['name'] = isset($getWeekList[$v]) ? $getWeekList[$v] : '';
                }
            }
        }else{
            if(isset($param['keyValue'])&&$param['keyValue']){
                $keyValue = explode(',',$param['keyValue']);
                foreach ($keyValue as $k=>$v){
                    $week_name[$k]['id'] = $v;
                    $week_name[$k]['name'] = $v;
                }
            }else{
                $identity_info_model = new \app\admin\model\IdentityInfo();
                $getWeekList = $identity_info_model->getWeekNameArrList();
                $week_name = $getWeekList;
            }
        }
        $result = ['total' => count($week_name), 'rows' => $week_name];
        return json($result);
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $appointment_time = $row['appointment_time'] ? explode(' - ',$row['appointment_time']) : [];
            $row['start_time'] = isset($appointment_time[0]) ? $appointment_time[0] : '';
            $row['end_time'] = isset($appointment_time[1]) ? $appointment_time[1] : '';
            // 获取学历选项数据
            $educationList = \app\admin\model\IdentityInfo::xl();

            //检查教师课程占用情况
            $ts = TeacherSubscribe::where(['teacher_id'=>$row['user_id']])->select();
            $identity_info_model = new \app\admin\model\IdentityInfo();
            $week_name_arr = $identity_info_model->getWeekList();
            $arr_c = [];
            foreach ($ts as $k=>$v){
                if($v['class_id']){
                    $tc = \app\admin\model\TeacherClass::where(['id'=>$v['class_id']])->find();
                    if($tc){
                        if(isset($arr_c[$tc['order_no']])&&$arr_c[$tc['order_no']]){
                            $week = ','.$week_name_arr[$v['week']];
                            $arr_c[$tc['order_no']] .= $week;
                        }else{
                            $arr_c[$tc['order_no']] = $week_name_arr[$v['week']];
                        }
                    }
                }
            }
            $content = '';
            foreach ($arr_c as $k=>$v){
                $a = $v.'已被课程单号:'.$k.'的订单占用,';
                $content .= $a;
            }
            if($content){
                $content .= '无法选择';
            }
            $this->view->assign('zy', $content);
//            $this->view->assign('zy',$content);
            $this->view->assign('row', $row);
            $this->view->assign('educationList', $educationList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if($params['start_time']&&$params['end_time']){
            $params['appointment_time'] = $params['start_time'].' - '.$params['end_time'];
        }
        unset($params['start_time'],$params['end_time']);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $user = User::where(['id'=>$params['user_id']])->find();
            $params['name'] = $user['nickname'];
            
            // 如果有生日，根据生日计算年龄
            if (!empty($params['birthday'])) {
                $params['age'] = $this->calculateAge($params['birthday']);
            }
            
            if($row['appointment_time_week'] != $params['appointment_time_week']){
                $week = explode(',',$params['appointment_time_week']);
                $sub = TeacherSubscribe::up_subscribe($week,$params['user_id']);
                if($sub['code'] == 0){
                    $this->error($sub['msg']);
                }
            }

            if($params['name']&&$params['phone']&&$params['health_certificate']&&$params['identity_card_img']&&$params['no_crime']){
                $params['is_all'] = '是';
            }else{
                $params['is_all'] = '否';
            }
            $result = $row->allowField(true)->save($params);
            
            // 提交事务后，添加队列任务生成Word文档
            if ($result !== false && $row['identity_type'] == '教师') {
                // 使用队列异步生成Word文档
                $detail = \app\admin\model\TeacherDetail::where(['info_id'=>$row['id']])->select();
                foreach ($detail as $k=>$v){
                    \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $params['user_id'],'detail_id'=>$v['id']], 'default');
                }
                if(!$detail){
                    \think\Queue::push('app\\job\\GenerateTeacherWordJob', ['user_id' => $params['user_id']], 'default');
                }
            }
            
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 根据生日计算年龄
     * @param string $birthday 生日 YYYY-MM-DD 格式
     * @return int 年龄
     */
    private function calculateAge($birthday)
    {
        $today = new \DateTime();
        $birthDate = new \DateTime($birthday);
        $age = $today->diff($birthDate)->y;
        return $age;
    }

}
